
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import make_item


class JiangxiYtsyjqrmzf0898Policy(BaseTaxPolicySpider):
    name = "jiangxi_ytsyjqrmzf_0898_policy"
    province: str = "江西省"  # 取表格
    city: str = "鹰潭市"  # 取表格
    county: str = "余江区"  # 取表格
    park: str = ""  # 取表格
    source: str = "鹰潭市余江区人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.yujiang.gov.cn/col/col4571/index.html?vc_xxgkarea=Y02000&number=%20Y12001Y12002Y12003"  # 注明入口网址，以便后续排错
    auto_next: bool = True

    def start_requests(self):
        url = "http://www.yujiang.gov.cn/module/xxgk/search.jsp?"
        params = {'currpage': '1'}
        for infotypeId in [' Y12001Y12002Y12003']:
            data = {'infotypeId': infotypeId, 'divid': 'div4'}
            yield from self.gen_request_by_search_jsp(
                url=url, params=params, data=data, callback=self.parse_content, auto_next=self.auto_next, parse_response=self.parse_response
            )

    def parse_response(self, response, **kwargs):
        callback = kwargs.get("callback")
        list_select = response.xpath("//td")
        for i in list_select.xpath("./a[@title]"):
            url = i.xpath("./@href").get()
            yield self.Request(url, callback=callback)

    def parse_content(self, response, **kwargs):
        pre_data = self.parse_title_and_publish_time_by_gen(response.text)
        title = pre_data.get("title")
        publish_date = (
            response.xpath('//*[@name="PubDate"]/@content').get()
            or response.xpath('//*[@name="pub_date"]/@content').get()
            or pre_data.get("publish_time")
        )
        content = response.text
        content = self.process_content(content)

        item = dict(
            title=title,
            publish_date=publish_date,
            content=content,
            source_url=response.url,
            source=self.source,
            province=self.province,
            city=self.city,
            county=self.county,
            park=self.park,
        )
        yield make_item(NetTaxPolicyItem, item)


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jiangxi_ytsyjqrmzf_0898_policy".split())
